package com.wm.javamall.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wm.common.to.mq.OrderTo;
import com.wm.common.utils.PageUtils;
import com.wm.common.utils.Query;
import com.wm.common.utils.R;
import com.wm.common.vo.MemberRespVo;
import com.wm.javamall.cart.controller.CartController;
import com.wm.javamall.cart.service.CartService;
import com.wm.javamall.cart.vo.CartItem;
import com.wm.javamall.config.AlipayTemplate;
import com.wm.javamall.interceptor.LoginUserInterceptor;
import com.wm.javamall.member.controller.MemberReceiveAddressController;
import com.wm.javamall.member.entity.MemberReceiveAddressEntity;
import com.wm.javamall.member.service.MemberReceiveAddressService;
import com.wm.javamall.order.constant.OrderConstant;
import com.wm.javamall.order.dao.OrderDao;
import com.wm.javamall.order.dao.OrderItemDao;
import com.wm.javamall.order.entity.OrderEntity;
import com.wm.javamall.order.entity.OrderItemEntity;
import com.wm.javamall.order.entity.PaymentInfoEntity;
import com.wm.javamall.order.entity.RefundInfoEntity;
import com.wm.javamall.order.enums.OrderStatusEnum;


import com.wm.javamall.order.service.*;
import com.wm.javamall.order.to.OrderCreateTo;
import com.wm.javamall.order.vo.*;
import com.wm.javamall.product.controller.SpuInfoController;
import com.wm.javamall.product.service.SkuSaleAttrValueService;
import com.wm.javamall.ware.controller.WareSkuController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    OrderItemDao orderItemDao;

    @Autowired
    MemberReceiveAddressController memberReceiveAddressController;

    @Autowired
    MemberReceiveAddressService memberReceiveAddressService;

    @Autowired
    WareSkuController wareSkuController;

    @Autowired
    CartService cartService;
    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    SpuInfoController spuInfoController;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    AlipayTemplate alipayTemplate;

    @Autowired
    RefundInfoService refundInfoService;

    @Autowired
    OrderReturnApplyService orderReturnApplyService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<OrderEntity>().orderByDesc("create_time");
        if (!StringUtils.isEmpty(params.get("orderSn"))){
            wrapper.eq("order_sn", params.get("orderSn"));
        }
        if (!StringUtils.isEmpty(params.get("memberUsername"))){
            wrapper.eq("member_username", params.get("memberUsername"));
        }
        if (!StringUtils.isEmpty(params.get("status"))){
            wrapper.eq("status", params.get("status"));
        }
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 订单确认页返回需要用的数据
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder(){
        try {
            OrderConfirmVo confirmVo = new OrderConfirmVo();
            MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
            log.info("service_member={}", memberRespVo);

            CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
                //1、查询所有收货地址列表
                //设置主线程中的数据
                List<MemberReceiveAddressEntity> addressEntities = memberReceiveAddressController.getAddress(memberRespVo.getId());
                confirmVo.setAddress(addressEntities);
            }, executor);

            CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
                //2、查询购物车所有选中的购物项
                //设置主线程中的数据

                List<CartItem> cartItems = cartService.getUserCartItems(memberRespVo);

                confirmVo.setItems(cartItems);
                //feign在远程调用之前要构造请求，调用很多的拦截器
            }, executor).thenRunAsync(() -> {
                List<CartItem> items = confirmVo.getItems();
                List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());

                R hasStock = wareSkuController.getSkuHasStock(collect);
                List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
                });
                if (data != null) {
                    Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                    confirmVo.setStocks(map);
                }
            }, executor);


            //3、查询用户积分
            Integer integration = memberRespVo.getIntegration();
            confirmVo.setIntegration(integration == null ? 0 :integration);

            //防重令牌
            String token = UUID.randomUUID().toString().replace("-", "");
            // 令牌添加入redis
            redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
            confirmVo.setOrderToken(token);

            CompletableFuture.allOf(getAddressFuture, cartFuture).get();

            return confirmVo;
        } catch (Exception e) {
            log.error("生成订单确认页失败：",e);
            return null;
        }
    }

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        submitVoThreadLocal.set(vo);

        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        response.setCode(0);

        //1、验证令牌【令牌的对比和删除必须保证原子性】
        //0令牌失败，1删除成功
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();

        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result == 0L) {
            //失败
            response.setCode(1);
            return response;
        } else {
            //令牌验证成功
            //1、创建订单，订单项等信息
            OrderCreateTo order = createOrder(memberRespVo);
            //2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比
                //3、保存订单
                saveOrder(order);
                //4、库存锁定,只要有异常回滚订单数据。
                // 订单号，所有订单项（skuId,skuName,num）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                com.wm.javamall.ware.vo.WareSkuLockVo lockVo1 = new com.wm.javamall.ware.vo.WareSkuLockVo();
                BeanUtils.copyProperties(lockVo, lockVo1);

                //问题：库存成功了，但是网络原因超时了，订单回滚，库存不回滚
                //为了保证高并发，库存服务自己回滚，可以发消息个库存服务；
                //库存服务本身也可以自动解锁模式 使用消息队列
                R r = wareSkuController.orderLockStock(lockVo1);
                if(r.getCode() == 0){
                    //锁成功了
                    response.setOrder(order.getOrder());
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return response;
                } else {
                    //锁定失败
                    log.error("商品库存不足，OrderSubmitVo={}",vo);
                    response.setCode(3);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return response;
                }
            } else {
                response.setCode(2);
                return response;
            }
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));

        return order_sn;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageWithItem2(Integer pageNum) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<OrderEntity>()
                .eq("member_id", memberRespVo.getId()).orderByDesc("id");

        Page<OrderEntity> page = baseMapper.selectPage(new Page<>(pageNum, 10), wrapper);
        List<OrderEntity> orderEntities = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderEntities);
        return new PageUtils(page);
    }

    /**
     * 获取订单详情页信息
     * @param orderSn
     */
    @Override
    public OrderEntity getOrderDetail(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        wrapper.eq("member_id", memberRespVo.getId());
        OrderEntity orderEntity = this.getOne(wrapper);
        List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderEntity.getOrderSn()));
        orderEntity.setItemEntities(orderItemEntities);
        return orderEntity;
    }

    @Override
    public void updateOrder(OrderEntity order) {

        if (order.getStatus() == OrderStatusEnum.SENDED.getCode() && StringUtils.isEmpty(order.getDeliveryTime())){
            //已发货状态
            order.setDeliveryTime(new Date());
            if (StringUtils.isEmpty(order.getDeliveryCompany())){
                order.setDeliveryCompany("普通快递");
            }
        }
        if (order.getStatus() == OrderStatusEnum.SERVICED.getCode()){
            // 更新为售后完成状态
            // 解锁库存
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order,orderTo);
            try {
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",order);
            } catch (AmqpException e) {
                log.error("订单售后完成：发送解锁库存消息失败！", e);
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",order);
            }
        }
        order.setModifyTime(new Date());
        this.updateById(order);

    }

    @Override
    public void closeOrder(OrderEntity entity) {
        // 更新支付状态
        String payResult = handlePayResult(entity.getOrderSn());
        if (payResult.equals("success")){
            log.info("订单已支付，无需取消订单。");
            return;
        }
        //查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if(orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCEL.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //发给MQ一个
            try {
                //关单后解锁库存
                log.info("发送关单解锁库存消息！orderTo={}", orderTo);
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other.unlock", orderTo);
            } catch (Exception e) {
                log.error("发送关单解锁库存消息失败！",e);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancelOrder(String orderSn) {
        //查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        if(orderEntity.getStatus() == OrderStatusEnum.PAYED.getCode()){
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCEL.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            orderTo.setOrderSn(orderSn);
            log.info("发送关单解锁库存消息！orderTo={}", orderTo);
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other.unlock", orderTo);
            // 退款
            AlipayTradeRefundResponse response = alipayTemplate.refund(orderSn, orderEntity.getPayAmount());
            RefundInfoEntity refundInfo = new RefundInfoEntity();
            if(response.isSuccess()){
                // 保存退款信息
                refundInfo.setRefundSn(response.getTradeNo());
                refundInfo.setRefund(new BigDecimal(response.getRefundFee()));
                refundInfo.setOrderReturnId(response.getOutTradeNo());
                refundInfo.setRefundStatus(1);
                refundInfoService.save(refundInfo);
            } else {
                refundInfo.setRefundSn(response.getTradeNo());
                refundInfo.setRefund(new BigDecimal(response.getRefundFee()));
                refundInfo.setOrderReturnId(response.getOutTradeNo());
                refundInfo.setRefundStatus(0);
                refundInfoService.save(refundInfo);
                throw new RuntimeException("退款失败");
            }
        } else if (orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            // 待支付
            //关单
            closeOrder(orderEntity);
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void confirmReceipt(String orderSn) {
        //查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        if(orderEntity.getStatus() == OrderStatusEnum.SENDED.getCode()){
            //确认收货
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.RECEIVED.getCode());
            update.setConfirmStatus(1);
            this.updateById(update);
            // 减去库存
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            try {
                // 减库存可以用 异步 的 消息队列
//                wmsFeignService.minusWare(orderEntity);
                log.info("减库存消息发送！");
                rabbitTemplate.convertAndSend("stock-event-exchange","stock.minus",orderTo);
            } catch (Exception e) {
                log.error("减库存消息发送失败！",e);
            }
        }
    }


    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);

        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());

        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = order_sn.get(0);
        payVo.setSubject(entity.getSkuName());
        payVo.setBody(entity.getSkuAttrsVals());
        return payVo;
    }

    /**
     * 处理支付宝的支付结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(infoEntity);

        //2、修改订单的状态信息
        if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功状态
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String handlePayResult(String orderSn) {

        AlipayTradeQueryResponse response = alipayTemplate.queryPayResult(orderSn);
        if (!ObjectUtils.isEmpty(response)){
            if(response.isSuccess()){
                log.info("支付宝订单查询接口,PayAmount={}, TradeStatus={}, OutTradeNo={}, BuyerLogonId={}, BuyerPayAmount={}",
                        response.getPayAmount(), response.getTradeStatus(), response.getOutTradeNo(), response.getBuyerLogonId(), response.getBuyerPayAmount());
                String tradeStatus = response.getTradeStatus();

                //1、保存交易流水
                PaymentInfoEntity infoEntity = new PaymentInfoEntity();
                infoEntity.setAlipayTradeNo(response.getTradeNo());
                infoEntity.setOrderSn(response.getOutTradeNo());
                infoEntity.setPaymentStatus(response.getTradeStatus());
                infoEntity.setCallbackTime(response.getSendPayDate());
                infoEntity.setCreateTime(new Date());
                infoEntity.setSubject(response.getSubject());
                infoEntity.setTotalAmount(new BigDecimal(response.getBuyerPayAmount()));
                // 响应信息太长
//                infoEntity.setCallbackContent(JSONObject.toJSONString(response));

                paymentInfoService.save(infoEntity);
                // 支付成功
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)){
                    //支付成功状态
                    String outTradeNo = response.getOutTradeNo();
                    this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
                    return "success";
                } else {
                    return "fail";
                }
            } else {
                return "error";
            }
        } else {
            return "error";
        }
    }



    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
//        orderItemService.saveBatch(orderItems);
        //使用批量保存（没有导入seata前正常）时出现问题：
        // Error updating database.  Cause: io.seata.common.exception.NotSupportYetException
        //使用普通的保存方法，不使用seata可重新修改回来
        for (OrderItemEntity orderItem : orderItems) {
            orderItemDao.insert(orderItem);
        }
    }

    private OrderCreateTo createOrder(MemberRespVo memberRespVo) {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);

        //2、获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn, memberRespVo);

        //3、验价,计算价格相关
        computePrice(orderEntity, itemEntities);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(itemEntities);
        return orderCreateTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        //订单的总额，叠加每个订单项的总额信息
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));

        }
        //1、订单价格相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0); //0:未删除
    }

    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberRespVo.getId());
        entity.setMemberUsername(memberRespVo.getUsername());
        //获取收货地址信息
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        MemberReceiveAddressEntity memberReceiveAddress = memberReceiveAddressService.getById(orderSubmitVo.getAddrId());
        //设置运费信息
        entity.setFreightAmount(BigDecimal.ZERO);
        //设置收货人信息
        entity.setReceiverCity(memberReceiveAddress.getCity());
        entity.setReceiverDetailAddress(memberReceiveAddress.getDetailAddress());
        entity.setReceiverName(memberReceiveAddress.getName());
        entity.setReceiverPhone(memberReceiveAddress.getPhone());
        entity.setReceiverProvince(memberReceiveAddress.getProvince());
        entity.setReceiverRegion(memberReceiveAddress.getRegion());
        entity.setReceiverPostCode(memberReceiveAddress.getPostCode());

        //设置订单的状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }

    /**
     * 构建所有订单项数据
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn, MemberRespVo memberRespVo) {
        //最后确认每个购物项的价格
        List<CartItem> cartItems = cartService.getUserCartItems(memberRespVo);

        if (cartItems != null && cartItems.size() > 0) {
            List<OrderItemEntity> itemEntities = cartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }
    /**
     * 构建某一个订单
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(CartItem cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息：订单号
        //2、商品的SPU信息
        Long skuId = cartItem.getSkuId();
        R r = spuInfoController.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());
        //3、商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息（不做）
        //5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额,总额-各种优惠
        BigDecimal origin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = origin.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());

        itemEntity.setRealAmount(subtract);

        return itemEntity;
    }
}